package com.hzcx.app.simplechat.ui.setting;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.common.CommonSp;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.setting.adapter.SettingAutoSendMsgAdapter;
import com.hzcx.app.simplechat.ui.setting.bean.AutoSendMessageBean;
import com.hzcx.app.simplechat.ui.setting.contract.SettingAutoSendMsgContract;
import com.hzcx.app.simplechat.ui.setting.event.AddAutoSendMsgEvent;
import com.hzcx.app.simplechat.ui.setting.presenter.SettingAutoSendMsgPresenter;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.sp.SPUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 自动打招呼界面
 */
public class SettingAutoSendMsgActivity extends BaseActivity<SettingAutoSendMsgPresenter> implements SettingAutoSendMsgContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_auto_send_msg)
    TextView tvAutoSendMsg;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.rv_auto_msg)
    RecyclerView rvAutoMsg;
    @BindView(R.id.tv_add_auto_msg)
    TextView tvAddAutoMsg;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.cons_title)
    ConstraintLayout consTitle;
    @BindView(R.id.switch_auto_send_msg)
    Switch switchAutoSendMsg;

    private List<AutoSendMessageBean> messageData;
    private SettingAutoSendMsgAdapter msgAdapter;

    private boolean isMove = false;

    private boolean isAutoChatReady = true;

    @Override
    public int getLayout() {
        return R.layout.activity_setting_auto_send_msg;
    }

    @Override
    public void initPresenter() {
        mPresenter = new SettingAutoSendMsgPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("自动打招呼");
        ivTitleRight.setImageResource(R.mipmap.ic_icon_setting_auto_send_msg);
        tvTitleRight.setText("排序");

        if (UserInfoUtil.getUserAutoSendMessage() == 1) {
            switchAutoSendMsg.setChecked(true);
        }

        messageData = new ArrayList<>();
        msgAdapter = new SettingAutoSendMsgAdapter(messageData);
        rvAutoMsg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvAutoMsg.setAdapter(msgAdapter);
    }

    @Override
    public void initData() {
        mPresenter.getMessageSettingList(this, true);

        msgAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.iv_check_box:
                    mPresenter.updateMessageItemSetting(SettingAutoSendMsgActivity.this, messageData.get(position).getHost_id(), position);
                    break;

                case R.id.tv_delete:
                    mPresenter.deleteMessageSettingItem(SettingAutoSendMsgActivity.this, messageData.get(position).getHost_id(), position);
                    break;

                case R.id.tv_edit:
                    if (messageData.get(position).getHost_type() == 2) {
                        startActivity(new Intent(SettingAutoSendMsgActivity.this, AddAutoSendMsgImageActivity.class)
                                .putExtra(AddAutoSendMsgImageActivity.INTENT_ID, messageData.get(position).getHost_id() + "")
                                .putExtra(AddAutoSendMsgImageActivity.INTENT_CONTENT, messageData.get(position).getMaincontent())
                                .putExtra(AddAutoSendMsgImageActivity.INTENT_IMAGE, messageData.get(position).getHostimage()));
                    } else {
                        startActivity(new Intent(SettingAutoSendMsgActivity.this, AddAutoSendMsgTextActivity.class)
                                .putExtra(AddAutoSendMsgTextActivity.INTENT_ID, messageData.get(position).getHost_id() + "")
                                .putExtra(AddAutoSendMsgTextActivity.INTENT_CONTENT, messageData.get(position).getMaincontent()));
                    }
                    break;
            }
        });

        switchAutoSendMsg.setOnCheckedChangeListener((compoundButton, b) -> {
            if (!isAutoChatReady) {
                return;
            }
            isAutoChatReady = false;
            if (b) {
                mPresenter.updateAutoChat(SettingAutoSendMsgActivity.this, "1");
            } else {
                mPresenter.updateAutoChat(SettingAutoSendMsgActivity.this, "0");
            }
        });
    }

    @OnClick({R.id.tv_add_auto_msg, R.id.tv_title_right})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add_auto_msg: // 添加自动回复消息
                showAddDialog();
                break;

            case R.id.tv_title_right:
                if (!isMove) {
                    tvTitleRight.setText("完成");
                    helper.attachToRecyclerView(rvAutoMsg);
                    msgAdapter.setIsLeft(false);
                    isMove = true;
                } else {
                    mPresenter.moveMessageSetting(this, messageData);
                }
                break;
        }
    }

    /**
     * 添加自动回复弹窗
     */
    private void showAddDialog() {
        List<String> list = new ArrayList<>();
        list.add("文字");
        list.add("图文");
        PublicRoundDialog roundDialog = new PublicRoundDialog(this, "请选择", list, (pos, menu) -> {
            switch (menu) {
                case "文字":
                    startActivity(new Intent(SettingAutoSendMsgActivity.this, AddAutoSendMsgTextActivity.class));
                    break;

                case "图文":
                    startActivity(new Intent(SettingAutoSendMsgActivity.this, AddAutoSendMsgImageActivity.class));
                    break;
            }
        });
        roundDialog.show();
    }

    /**
     * 获取自动回复列表成功
     *
     * @param data
     */
    @Override
    public void messageResult(List<AutoSendMessageBean> data) {
        try {
            messageData.clear();
            messageData.addAll(data);
            msgAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 某一条消息自动回复状态修改成功
     *
     * @param pos
     */
    @Override
    public void updateItemSuccess(int pos) {
        if (messageData.get(pos).getIs_sel() == 1) {
            messageData.get(pos).setIs_sel(0);
        } else {
            messageData.get(pos).setIs_sel(1);
        }
        msgAdapter.notifyDataSetChanged();
    }

    /**
     * 删除某一条自动回复消息成功
     *
     * @param pos
     */
    @Override
    public void deleteSuccess(int pos) {
        messageData.remove(pos);
        msgAdapter.notifyDataSetChanged();
    }

    /**
     * 排序成功
     */
    @Override
    public void moveSuccess() {
        isMove = false;
        helper.attachToRecyclerView(null);
        msgAdapter.setIsLeft(true);
        tvTitleRight.setText("排序");
    }

    /**
     *  自动打招呼开关设置成功
     */
    @Override
    public void updateAutoSuccess() {
        isAutoChatReady = true;
        if (UserInfoUtil.getUserAutoSendMessage() == 1) {
            SPUtils.put(this, CommonSp.USER_AUTO_SEND_MESSAGE, 0);
        } else {
            SPUtils.put(this, CommonSp.USER_AUTO_SEND_MESSAGE, 1);
        }
    }

    /**
     *  自动打招呼开关设置失败
     */
    @Override
    public void updateAutoFail() {
        isAutoChatReady = true;
        switchAutoSendMsg.setChecked(!switchAutoSendMsg.isChecked());
    }

    /**
     * 刷新列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshMsgList(AddAutoSendMsgEvent event) {
        mPresenter.getMessageSettingList(this, false);
    }

    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFrlg = 0;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                dragFrlg = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            return makeMovementFlags(dragFrlg, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            //滑动事件  下面注释的代码，滑动后数据和条目错乱，被舍弃
//            Collections.swap(datas,viewHolder.getAdapterPosition(),target.getAdapterPosition());
//            ap.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());

            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(messageData, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(messageData, i, i - 1);
                }
            }
            msgAdapter.notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //侧滑删除可以使用；
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                //获取系统震动服务//震动70毫秒
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(70);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundColor(0);
            msgAdapter.notifyDataSetChanged();  //完成拖动后刷新适配器，这样拖动后删除就不会错乱
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
